import json
from datetime import datetime

from .getPublicData import *
import time

def getNowTime():
    timeFormat = time.localtime()
    year = timeFormat.tm_year
    month = timeFormat.tm_mon
    day = timeFormat.tm_mday
    return year,monthList[month-1],day


def getUserCreateTime():
    users = getAllUsers()
    data = {}
    for user in users:
        # 格式化时间，只保留年月日
        create_date = user.createTime.date()  # 转换为日期格式
        create_date_str = create_date.strftime('%Y-%m-%d')  # 格式化为字符串

        if data.get(create_date_str, -1) == -1:
            data[create_date_str] = 1
        else:
            data[create_date_str] += 1

    result = []
    for k, v in data.items():
        result.append({
            'name': k,
            'value': v
        })
    return result


def getUserTop6():
    users = getAllUsers()

    # 转换字符串为时间戳
    def sort_fn(item):
        if isinstance(item.createTime, str):
            return time.mktime(time.strptime(item.createTime, '%Y-%m-%d'))
        return time.mktime(item.createTime.timetuple())  # 如果是 datetime

    # 按时间降序排列，并取前6个用户
    users = list(sorted(users, key=sort_fn, reverse=True))[:6]
    return users


def getAllTags():
    jobs = JobInfo.objects.all()
    users = User.objects.all()
    educationTop = '学历不限'
    salaryTop = 0
    salaryMonthTop = 0
    address = {}
    internship = {0: 0, 1: 0}  # 初始化实习和日常岗位计数

    for job in jobs:
        # 处理学历字段
        if job.educational in educations and educations[job.educational] < educations[educationTop]:
            educationTop = job.educational

        # 解析工资字段
        try:
            salary = json.loads(job.salary)[1]
            if salaryTop < salary:
                salaryTop = salary
        except (TypeError, ValueError, IndexError) as e:
            print(f"Error parsing salary for job {job.id}: {e}")

        # 解析月薪字段
        try:
            salaryMonth = int(job.salaryMonth)
            if salaryMonth > salaryMonthTop:
                salaryMonthTop = salaryMonth
        except (ValueError, TypeError) as e:
            print(f"Error parsing salaryMonth for job {job.id}: {e}")

        # 统计岗位地址
        if job.address:
            address[job.address] = address.get(job.address, 0) + 1

        # 统计岗位性质
        if job.internship in internship:
            internship[job.internship] += 1

    # 排序地址并获取前三名
    addressStr = sorted(address.items(), key=lambda x: x[1], reverse=True)[:3]
    addressTop = ','.join([item[0] for item in addressStr]) if addressStr else "无数据"

    # 确定最多的岗位性质
    internshipMax = max(internship, key=internship.get, default=0)
    internshipLabel = '实习岗位' if internshipMax == 1 else '正常岗位'

    return len(jobs), len(users), educationTop, salaryTop, salaryMonthTop, addressTop, internshipLabel
def getAllJobsPBar():
    jobs = getAllJobs()
    tempData = {}
    for job in jobs:
        if tempData.get(str(job.createTime), -1) == -1:
            tempData[str(job.createTime)] = 1
        else:
            tempData[str(job.createTime)] += 1

    def sort_fn(item):
        item = list(item)
        return time.mktime(time.strptime(item[0], '%Y-%m-%d'))

    result = list(sorted(tempData.items(), key=sort_fn))
    def map_fn(item):
        item = list(item)
        item.append(round(item[1]/len(jobs),3))
        return item
    result = list(map(map_fn,result))
    return result

def getTableData():
    jobs = getAllJobs()
    for i in jobs:
        work_tag_list = json.loads(i.workTag)
        work_tag_filtered = [tag for tag in work_tag_list if tag.strip()]  # 去掉空字符串和空格
        i.workTag = '/'.join(work_tag_filtered)  # 合并为字符串
        if i.companyTags != '无':
            i.companyTags = '/'.join(json.loads(i.companyTags))
        if i.companyPeople == '[0, 10000]':
            i.companyPeople = '10000人以上'
        else:
            i.companyPeople = json.loads(i.companyPeople)
            i.companyPeople = list(map(lambda x:str(x)+'人',i.companyPeople))
            i.companyPeople = '-'.join(i.companyPeople)
        i.salary = json.loads(i.salary)[1]

    return jobs

